<template>
  <div class="admin-product-list">
    <!-- 顶部：标题 + 筛选栏 -->
    <div class="list-header">

      <!-- 筛选区 -->
      <div class="filter-container">
        <el-select
          v-model="filterCategory"
          placeholder="筛选分类"
          clearable
          class="filter-select"
      >
        <el-option label="全部分类" value="" />
        <el-option
            v-for="item in categoryOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
        />
      </el-select>
        <el-select
            v-model="filterStatus"
            placeholder="筛选状态"
            clearable
            class="filter-select"
        >
          <el-option label="全部" value="" />
          <el-option label="上架" value="1" />
          <el-option label="下架" value="0" />
        </el-select>
        <el-input
            v-model="searchKey"
            placeholder="搜索商品名称/ID"
            clearable
            class="search-input"
        />

        <el-button type="primary" @click="getProductList">查询</el-button>
      </div>
    </div>

    <!-- 中间：商品数据表格 -->
    <el-table
        :data="productList"
        border
        stripe
        row-key="id"
        :loading="isLoading"
        class="product-table"
    >
      <el-table-column label="序号" type="index" width="80" align="center" />
      <!-- 商品图片 -->
      <el-table-column label="商品主图" width="120" align="center">
        <template #default="scope">
          <el-image
              :src="scope.row.image_url"
              style="width: 60px; height: 60px; object-fit: cover"
              fit="cover"
          />
        </template>
      </el-table-column>
      <!-- 商品信息 -->
      <el-table-column label="商品信息" min-width="220">
        <template #default="scope">
          <div class="product-info">
            <p class="prod-name">{{ scope.row.prod_name }}</p>
            <p class="prod-desc">描述：{{ scope.row.prod_desc || '暂无描述' }}</p>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="分类" width="140" align="center" prop="category" />
      <!-- 价格 -->
      <el-table-column label="价格" width="120" align="center">
        <template #default="scope">
          <span class="price-tag">¥{{ scope.row.price.toFixed(2) }}</span>
        </template>
      </el-table-column>
      <!-- 库存 -->
      <el-table-column label="库存" width="120" align="center">
        <template #default="scope">
          <span :class="scope.row.store <= 10 ? 'low-stock' : ''">
            {{ scope.row.store }}
          </span>
        </template>
      </el-table-column>
      <!-- 状态 -->
      <el-table-column label="状态" width="120" align="center">
        <template #default="scope">
          <el-tag :type="Number(scope.row.status) === 1 ? 'success' : 'info'">
            {{ Number(scope.row.status) === 1 ? '上架' : '下架' }}
          </el-tag>
        </template>
      </el-table-column>
      <!-- 操作栏 -->
      <el-table-column label="操作" width="280" align="center">
        <template #default="scope">
          <el-button
              type="primary"
              size="small"
              icon="Edit"
              @click="openEditDialog(scope.row)"
          >
            编辑
          </el-button>
          <el-button
              :type="Number(scope.row.status) === 1 ? 'info' : 'success'"
              size="small"
              @click="toggleStatus(scope.row)"
              class="ml-2"
          >
            {{ Number(scope.row.status) === 1 ? '下架' : '上架' }}
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 底部：分页 -->
    <div class="list-pagination">
      <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="pageNum"
          :page-sizes="[4, 5, 6]"
          :page-size="pageSize"
          :total="totalCount"
          layout="total, sizes, prev, pager, next, jumper"
      />
    </div>

    <!--------------------------------------- 编辑商品弹窗----------------------------------------------- -->
    <el-dialog
        v-model="editDialogVisible"
        title="编辑商品"
        width="600px"
        :before-close="closeEditDialog"
    >
      <el-form
          ref="editFormRef"
          :model="editForm"
          label-width="120px"
          class="edit-form"
      >
        <!-- 商品ID（只读） -->
        <el-form-item label="商品ID">
          <el-input v-model="editForm.id" disabled />
        </el-form-item>
        <!-- 商品名称（必填） -->
        <el-form-item
            label="商品名称"
            prop="prod_name"
            :rules="[{ required: true, message: '请输入商品名称', trigger: 'blur' }]"
        >
          <el-input
              v-model="editForm.prod_name"
              placeholder="请输入商品名称"
              maxlength="50"
          />
        </el-form-item>
        <!-- 商品描述 -->
        <el-form-item label="商品描述" prop="desc">
          <el-input
              v-model="editForm.prod_desc"
              placeholder="请输入商品描述"
              type="textarea"
              rows="3"
              maxlength="200"
          />
        </el-form-item>
        <!-- 商品分类（必填） -->
        <el-form-item
            label="商品分类"
            prop="category"
            :rules="[{ required: true, message: '请选择商品分类', trigger: 'change' }]"
        >
          <el-select v-model="editForm.category" placeholder="请选择商品分类">
            <el-option
                v-for="item in categoryOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
            />
          </el-select>
        </el-form-item>
        <!-- 商品价格（必填） -->
        <el-form-item
            label="商品价格"
            prop="price"
            :rules="[
            { required: true, message: '请输入商品价格', trigger: 'blur' },
            { type: 'number', min: 0.01, message: '价格必须大于0', trigger: 'blur' }
          ]"
        >
          <el-input
              v-model.number="editForm.price"
              placeholder="请输入商品价格"
              type="number"
              step="0.01"
              precision="2"
          />
        </el-form-item>
        <!-- 商品库存（必填） -->
        <el-form-item
            label="商品库存"
            prop="store"
            :rules="[
            { required: true, message: '请输入商品库存', trigger: 'blur' },
            { type: 'integer', min: 0, message: '库存必须为非负整数', trigger: 'blur' }
          ]"
        >
          <el-input
              v-model.number="editForm.store"
              placeholder="请输入商品库存"
              type="number"
              step="1"
              min="0"
          />
        </el-form-item>
        <!-- 商品状态 -->
        <el-form-item label="商品状态" prop="status">
          <el-radio-group v-model="editForm.status">
            <el-radio :label="1">上架</el-radio>
            <el-radio :label="0">下架</el-radio>
          </el-radio-group>
        </el-form-item>
        <!-- 商品主图 -->
        <el-form-item label="商品主图" prop="image_url">
          <el-upload
              class="single-image-upload"
              :file-list="fileList"
              list-type="picture-card"
              :auto-upload="false"
              :on-change="handleFileChange"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              accept="image/*"
          >
            <div class="el-upload--picture-card" v-if="fileList.length === 0">
              <i class="el-icon-plus" />
            </div>
          </el-upload>
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="closeEditDialog">取消</el-button>
        <el-button type="primary" @click="submitEditForm">保存</el-button>
      </template>
    </el-dialog>

    <!-- 图片预览弹窗 -->
    <el-dialog v-model="previewVisible" title="图片预览" width="800px">
      <img
          :src="previewUrl"
          alt="商品图片预览"
          class="preview-img"
          style="width: 100%"
      />
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, reactive } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import ProductApi from '@/api/Product.js';
// 1. 图片上传相关
const fileList = ref([]);
const previewVisible = ref(false);
const previewUrl = ref('');
const ElConfirm = ElMessageBox.confirm;

// 2. 搜索筛选变量
const searchKey = ref('');
const filterCategory = ref('');
const filterStatus = ref('');
const categoryOptions = ref([
  { label: '手机数码', value: '手机数码' },
  { label: '家用电器', value: '家用电器' },
  { label: '美妆个护', value: '美妆个护' },
  { label: '食品生鲜', value: '食品生鲜' },
  { label: '家居家装', value: '家居家装' },
  { label: '图书音像', value: '图书音像' },
  { label: '运动户外', value: '运动户外' },
  { label: '母婴玩具', value: '母婴玩具' },
  { label: '汽车用品', value: '汽车用品' },
  { label: '虚拟服务', value: '虚拟服务' },
  { label: '其他', value: '其他' },
]);

// 3. 表格与分页变量
const productList = ref([]);
const isLoading = ref(false);
const totalCount = ref(0);
const pageNum = ref(1);
const pageSize = ref(5);

// 4. 编辑弹窗变量
const editDialogVisible = ref(false);
const editFormRef = ref(null);
const editForm = reactive({
  id: '',
  prod_name: '',
  prod_desc: '',
  category: '',
  price: 0,
  store: 0,
  status: 1,
  image_url: ''
});

// 5. 图片上传方法
const handleFileChange = (file, newFileList) => {
  if (newFileList.length > 1) {
    newFileList = [newFileList[newFileList.length - 1]];
    ElMessage.info('最多只能上传一张图片');
  }
  fileList.value = newFileList.map(item => ({ ...item, status: 'ready' }));
};

const handlePreview = (file) => {
  previewUrl.value = file.url || (file.raw ? URL.createObjectURL(file.raw) : editForm.image_url);
  previewVisible.value = true;
};

const handleRemove = (file,newFileList) => {
  ElConfirm('确定移除该图片吗？', '提示', { type: 'warning' })
      .then(() => {
        if (newFileList){
          fileList.value = newFileList;
        }
        editForm.image_url = '';
      })
      .catch(() => {
        fileList.value = [file];
        ElMessage.info('已取消移除')
      });
};

// 图片上传
const handleSubmitFiles = async () => {

  // 情况1：未选择任何图片（新图/旧图都没有）
  if (fileList.value.length === 0) {
    ElMessage.warning('请先选择要上传的商品图片');
    return false; // 阻断提交
  }

  const firstFile = fileList.value[0];
  console.log("图片上传文件：", firstFile.raw);
  // 情况2：是回显的旧图（raw为null）→ 无需重复上传，直接用旧URL
  if (firstFile.raw === null) {
    return true; // 返回成功，不触发上传接口
  }

  // 情况3：新选了图片（有raw）→ 执行上传，加异常捕获
  try {
    const avatar = await ProductApi.uploadAvatar(firstFile.raw);
    console.log("图片上传返回URL：", avatar); // 控制台看是否拿到正确URL
    editForm.image_url = avatar;
    return true;
  } catch (err) {
    // 打印完整错误，方便定位（是接口错、路径错还是参数错）
    console.error("图片上传失败详情：", err);
    ElMessage.error(`上传失败：${err.response?.data?.message || err.message}`);
    return false;
  }
};

// 6. 获取商品列表（核心修复：适配原axios数据结构）
const getProductList = async () => {
  isLoading.value = true;
  try {
    const query = {
      prod_name: searchKey.value.trim() || '',
      category: filterCategory.value || '',
      //...(条件) && { 属性: 值 },仅在filterStatus是'1'或'0'时，才添加属性status
      //相当于if(条件){属性:值}
      ...(filterStatus.value === '1' || filterStatus.value === '0') && {
        status: Number(filterStatus.value)  // 转为数字 1/0，符合后端参数类型
      },
      pageNum: Number(pageNum.value) || 1,
      pageSize: Number(pageSize.value) || 10
    };
    const res = await ProductApi.getProducts(query);
    // 原axios返回的是后端data对象（包含total、list等）
    productList.value = res.list;
    totalCount.value = res.total;
  } finally {
    console.log("所有商品的 id：", productList.value.map(item => item.id));
    isLoading.value = false;
  }
};

// 7. 编辑弹窗方法
const openEditDialog = (row) => {
  const rowCopy = JSON.parse(JSON.stringify(row));
  rowCopy.status = Number(rowCopy.status);
  Object.assign(editForm, rowCopy);


  if (editForm.image_url) {
    fileList.value = [{
      url: editForm.image_url,
      name: '已上传图片',
      status: 'success',
      raw: null
    }];
  } else {
    fileList.value = [];
  }
  editDialogVisible.value = true;
};

const closeEditDialog = () => {
  editDialogVisible.value = false;
  if (editFormRef.value) editFormRef.value.resetFields();
  fileList.value = [];
};

// 8. 提交编辑（适配原axios逻辑）
const submitEditForm = async () => {
  try {
    await editFormRef.value.validate();
  } catch (err) {
    ElMessage.warning('请完善表单信息');
    return;
  }
  const uploadSuccess = await handleSubmitFiles();
  if (!uploadSuccess) return;

  isLoading.value = true;
  try {
    const submitData = {
      ...editForm,
      status: Number(editForm.status),
      price: Number(editForm.price),
      store: Number(editForm.store)
    };
    // 原axios已处理code判断，成功才会执行后续
    await ProductApi.editProduct(submitData);
    closeEditDialog();
    await getProductList();
  } finally {
    isLoading.value = false;
  }
};

// 9. 切换商品状态
const toggleStatus = async (product) => {
const productId=product.id;
  const currentStatus = Number(product.status);
  const newStatus = currentStatus === 1 ? 0 : 1;
  const statusText = newStatus === 1 ? '上架' : '下架';

  try {
    await ElConfirm(`确定要${statusText}该商品吗？`, '提示', { type: 'info' });
    await ProductApi.updateStatus({
      id: productId,
      status: newStatus
    });
    product.status = newStatus;
    ElMessage.success(`${statusText}成功`);
  } catch (err) {
    ElMessage.info(`已取消${statusText}`);
  }
};

// 10. 分页方法
const handleSizeChange = (val) => {
  pageSize.value = val;
  pageNum.value = 1;
  getProductList();
};

const handleCurrentChange = (val) => {
  pageNum.value = val;
  getProductList();
};

// 11. 页面挂载
onMounted(() => {
  getProductList();
});
</script>

<style scoped>
.list-header { margin-bottom: 20px; }
.filter-container {
  display: flex;
  gap: 10px;
  align-items: center;
  margin-top: 15px;
  flex-wrap: wrap;
}
.search-input { width: 400px;text-align: center }
.filter-select { width: 400px;  }
.product-table { margin-bottom: 20px; width: 100%; }
.product-info { line-height: 1.5; }
.prod-name { font-weight: 500; margin-bottom: 4px; }
.prod-desc { color: #666; font-size: 12px; word-break: break-all; }
.price-tag { color: #f56c6c; font-weight: 500; }
.low-stock { color: #e6a23c; font-weight: 500; }
.list-pagination { text-align: right; margin-top: 15px; }
.edit-form { margin-top: 15px; }
.single-image-upload .el-upload--picture-card { width: 120px; height: 120px; }
.preview-img { max-height: 600px; object-fit: contain; }
</style>